<?php
namespace app\admin\controller;
use app\admin\model\Admin as AdminModel;
use think\Controller;
use think\Db;
use think\facade\Session;
class Login extends  Controller {                //普通用户登录判断
    protected  $beforeActionList=[
                        'checked_login'=>[
                            'only'=>'login'
                        ]
    ];
    public function checked_login(){
        if(!Session::get('cj')){
            $this->error('您未登录，请先登录!','login/login/login');
        }
    }
    public function login(){
        if(input('')==null) {                    //界面无任何值提交则到登录界面
            return $this->fetch('login/login');
        }else{
            $user=input('user');//获取前端提交数据
            $id = Db::table('ei_admin')->where('username',$user)->value('id');//获取登录用户的id
            $psd=input('psd');
            $captcha=input('captcha');
            if($this->check_captcha($captcha)){//判定返回结果是否正确
                if($this->check_login($user,$psd)){
                    session('cj',$user);                  //获取Session登录后的用户
                    session('id',$id);
                    return json(["res"=>2,"msg"=>'登录成功']);
                }else{
                    return json(["res"=>3,"msg"=>'账户或者密码错误']);
                }
            }else{
                return json(["res"=>1,"msg"=>'验证码错误']);
            }
        }
    }
    public function check_captcha($captcha){//验证验证码是否正确
        if(!captcha_check($captcha)){//判断验证
            return false;
        }else{
            return true;
        }
    }
    public function check_login($user,$psd){//判断账号密码是否正确
        //$result=AdminModel::where('username','login')->find();
        $result=AdminModel::where('username',$user)->value('password');//根据user查找结果
        if($result!=null){
            if($result==md5($psd)){
                return true;
            }else{
                return false;
            }
        }
    }

    public function admin(){
         return $this->fetch('/login/show');
    }
    public function out(){                   //退出登录
        Session::set('cj','');
        $this->success('退出登录中...','login/login/login');
    }
}